package pro.cherish.knowledgeutil.Dfa;

import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.*;
import java.util.stream.Collectors;


// fixme 参考博客
//https://www.cnblogs.com/zyguo/p/4705086.html
/**
 * @author 创建人：lys
 * @version 版本号：V1.0
 * <p>
 * ***************************修订记录************************************
 * 2020-6-3 lys 创建该类功能。
 * **********************************************************************
 * </p>
 * @ClassName 类名：DfaUtil
 * @Description 功能说明：
 * <p>
 * TODO
 * </p>
 * **********************************************************************
 * @date 创建日期： 2020-6-3 
 */
@Slf4j
public class DfaUtil {
	public static void main(String[] args) {
		String[] strings = {"中国国人"};
		Set<String> collect = Arrays.stream(strings).collect(Collectors.toSet());
		Map<Object, Object> dosomething = dosomething(collect);
		System.out.println(dosomething);
	}

	/**
	 * 读取敏感词库，将敏感词放入HashSet中，构建一个DFA算法模型：<br>
	 * 中 = {
	 *  isEnd = 0
	 *  国 = {<br>
	 *   isEnd = 1
	 *   人 = {isEnd = 0
	 *    民 = {isEnd = 1}
	 *    }
	 *   男 = {
	 *     isEnd = 0
	 *     人 = {
	 *      isEnd = 1
	 *      }
	 *    } [ 0-9]
	 *   }
	 *  }
	 * 五 = {
	 *  isEnd = 0
	 *  星 = {
	 *   isEnd = 0
	 *   红 = {
	 *    isEnd = 0
	 *    旗 = {
	 *     isEnd = 1
	 *     }
	 *    }
	 *   }
	 *  }
	 * @author chenming
	 * @date 2014年4月20日 下午3:04:20
	 * @param keyWordSet 敏感词库
	 * @version 0
	 */
	public static Map<Object, Object> dosomething(Set<String> keyWordSet) {
		HashMap<Object, Object> sensitiveWordMap  = new HashMap<>();
		log.info(keyWordSet.toString());
		Iterator<String> iterator = keyWordSet.iterator();
		while (iterator.hasNext()) {
			HashMap<Object, Object> map = sensitiveWordMap;
			// 中国人
			String word = iterator.next();
			// ['中',"国","人"]
			char[] chars = word.toCharArray();
			for (int i = 0; i < chars.length; i++) {
				char aChar = chars[i];
				Object wordMap = map.get(aChar);
				if (ObjectUtil.isNull(wordMap)) {
					Map<Object, Object> newMap = new HashMap<>();
					newMap.put("isEnd", 0);
					map.put(aChar, newMap);
					map = (HashMap<Object, Object>) newMap;
				} else {
					map = (HashMap<Object, Object>) wordMap;
				}
				if (i == chars.length - 1) {
					map.put("isEnd", 1);
				}
			}
		}
		return sensitiveWordMap;
	}


}
